from svn_controller import SvnController
from script_runner import executeCommand
import time

###############################################################################

class ProjectController:

    def __init__( self ):
        self.svnController = SvnController()
        self.svnController.setUsername( 'anastasia' )
        self.svnController.setPassword( '1' )
        self.commandLine = "ls -l"
        self.repoUrl = "svn://localhost/home/anastasia/dev/svnrepo"
        self.repoPath = "/home/anastasia/tmp/svnrepo"
        self.lastRevision = -1
        self.buildNumber = 0
        
        
###############################################################################


    def run( self ):
        
        if ( not self.svnController.checkURL( self.repoUrl ) ):
            print "Connection to SVN server failed"
            return

        while( True ):
            currentRevision = self.svnController.getHeadRevision( self.repoUrl )
            if ( currentRevision > self.lastRevision ):
                self.runBuild()
            else:
                time.sleep( 60 )
            
            
###############################################################################


    def runBuild( self ):
        self.buildNumber += 1
        workingRevision = -1
        
        if ( not self.svnController.checkWorkingCopy( self.repoPath ) ):
            workingRevision = self.svnController.checkout( self.repoUrl, self.repoPath )
            print "Checkout from", self.repoUrl, "to", self.repoPath, "revision:", workingRevision
        else:
            workingRevision = self.svnController.update( self.repoPath )
            print "Update", self.repoPath, "revision:", workingRevision
            
        if ( workingRevision == -1 ):
            print "build", self.buildNumber, "Failed"
            return
        
        self.lastRevision = workingRevision
        
        out, err, res = executeCommand( self.commandLine )
        print "out: ", out
        print "errors: ", err
        print "result: ", res
        if ( res == 0 ):
            print "build", self.buildNumber, "Done"
        else:
            print "build", self.buildNumber, "Failed"
        
        
###############################################################################

        